package com.yupi.yuojbackendgateway.filter;

import cn.hutool.core.text.AntPathMatcher;
import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWTUtil;
import com.yupi.yuojbackendcommon.common.ErrorCode;
import com.yupi.yuojbackendcommon.exception.BusinessException;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component
public class GlobalAuthFilter implements GlobalFilter, Ordered {

    private static final Logger logger = LoggerFactory.getLogger(GlobalAuthFilter.class);

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest serverHttpRequest = exchange.getRequest();
        String path = serverHttpRequest.getURI().getPath();

        // 日志输出当前请求路径
        logger.info("Request Path: {}", path);

        // 判断路径中是否包含 inner，只允许内部调用
        if (antPathMatcher.match("/**/inner/**", path)) {
            logger.warn("Unauthorized access to internal path: {}", path);
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.FORBIDDEN);
            DataBufferFactory dataBufferFactory = response.bufferFactory();
            DataBuffer dataBuffer = dataBufferFactory.wrap("无权限".getBytes(StandardCharsets.UTF_8));
            return response.writeWith(Mono.just(dataBuffer));
        }

        // 放行包含 'login' 的路径 (模糊匹配)
        if (antPathMatcher.match("/**/login/**", path)) {
            logger.info("Allowing login path: {}", path);
            return chain.filter(exchange);
        }
        // 放行包含 'register' 的路径 (模糊匹配)
        if (antPathMatcher.match("/**/register/**", path)) {
            logger.info("Allowing login path: {}", path);
            return chain.filter(exchange);
        }

        // 放行接口文档路径
        if (antPathMatcher.match("/**/api/**", path) || path.equals("/doc.html")) {
            logger.info("Allowing documentation path: {}", path);
            return chain.filter(exchange);
        }

        // 对于非内部调用，使用jwt来校验权限
        String token = serverHttpRequest.getHeaders().getFirst("token");
        if (StrUtil.isBlank(token)) {
            logger.warn("Missing or invalid token for path: {}", path);
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数错误");
        }
        try {
            JWTUtil.parseToken(token);
        } catch (Exception e) {
            logger.error("Invalid or expired token for path: {}, Error: {}", path, e.getMessage());
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR, "未登录或令牌过期");
        }

        logger.info("Token validation successful for path: {}", path);
        return chain.filter(exchange);
    }

    /**
     * 优先级提到最高
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}